package org.ChrisRiffle.Acme.AcmeTraverser;

import java.io.File;
import java.util.ArrayList;
import java.util.List;



/**
 * 
 * Class that traverses a directory structure, and calls a 
 * 'perform' method upon all its registered {@link ActionPerformer} objects
 * 
 * @author RIF
 * 
 */
public enum TraverserControler {
	
	//singleton
	INSTANCE;

	/**
	 * List of objects that will act upon files that are traversed 
	 * by this {@link TraverserControler} object
	 */
	private List<ActionPerformer> actionPerformerList; 



	/**
	 * Sets the {@link ActionPerformer} list
	 * 
	 * @param pActionPerformerList
	 * 					The {@link ActionPerformer} list
	 */
	public void setActionPerformerList(List<ActionPerformer> pActionPerformerList){
		
		actionPerformerList = pActionPerformerList;
	}
	
	
	/**
	 * Adds an {@link ActionPerformer}
	 * 
	 * @param pActionPerformer
	 * 				The {@link ActionPerformer} to add
	 */
	public void addActionPerformer(ActionPerformer pActionPerformer){
		
		getActionPerformerList().add(pActionPerformer);
	}
	
	
	/**
	 * Traverses the file system
	 * 
	 * @param pFile
	 * 			Either a File, or a top directory that will be 
	 * 			recursively traversed to perform actions upon its children
	 */
	public void traverse(File pFile) {

		if (pFile.isDirectory()) {
						
			File dirChildArray[] = pFile.listFiles();
			
			if(dirChildArray == null){
				// rare case: likely that access was denied 
				// to a system folder
				return;
			}
			
			for (File iFile : dirChildArray) {
				
				traverse(iFile);
			}
			
		} else if (pFile.isFile()) {
			
			for(ActionPerformer iPerformer : getActionPerformerList()){
				iPerformer.doAction(pFile);
			}
			
			
		}
		
		
	}
	
	/**
	 * Shuts down all the registered {@link ActionPerformer} objects
	 */
	public void shutDownPerformers(){
		
		for(ActionPerformer performer : getActionPerformerList()){
			performer.shutDown();
		}
		
	}
	


	
	/**
	 * Gets a never-null list of {@link ActionPerformer} objects
	 * @return
	 * 		never-null list of {@link ActionPerformer} objects
	 */
	public List<ActionPerformer> getActionPerformerList(){
		
		if(actionPerformerList == null){
			
			actionPerformerList = new ArrayList<ActionPerformer>();
		}
		return actionPerformerList;				
	}

}


